package org.lifei.gift.controller;

import com.baomidou.mybatisplus.plugins.Page;
import org.lifei.gift.dto.UserRegisterDTO;
import org.lifei.gift.service.IUserService;
import org.lifei.gift.domain.User;
import org.lifei.query.UserQuery;
import org.lifei.util.AjaxResult;
import org.lifei.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    public IUserService userService;


    /**
     * 保存和修改公用的
     * @param user  传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user){
        if( user.getId()!=null)
            userService.updateById(user);
        else
            userService.insert(user);
        return AjaxResult.me();
    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
            userService.deleteById(id);
        return AjaxResult.me();
    }
	
    //获取用户
    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable("id")Long id)
    {
        User user = userService.selectById(id);
        return AjaxResult.me().setResultObj(user);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping
    public AjaxResult list(){

        List< User> list = userService.selectList(null);
        return AjaxResult.me().setResultObj(list);
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */

    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public AjaxResult json(@RequestBody UserQuery query)
    {
        Page<User> page = new Page<User>(query.getPage(),query.getRows());
        page = userService.selectPage(page);
        PageList pageList = new PageList<User>(page.getTotal(),page.getRecords());
        return AjaxResult.me().setResultObj(pageList);
    }
    @PostMapping("/register")
    public AjaxResult register(@Valid @RequestBody UserRegisterDTO dto){
        userService.register(dto);
        return AjaxResult.me();
    }
}
